package com.clx.weblog.module.jwt.utils;

import com.clx.weblog.common.utils.Response;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.HttpStatus;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class ResultUtil {
    /**
     * 成功响参
     * @param response
     * @param result
     * @throws IOException
     * 将一个java对象序列化为HSON，并以HTTP响应的方式返回给前段
     */
    public static void ok(HttpServletResponse response, Response<?> result) throws IOException {
        // 设置响应编码格式
        response.setCharacterEncoding("UTF-8");
        // 设置响应状态吗
        response.setStatus(HttpStatus.OK.value());
        // 设置响应类型为json
        response.setContentType("application/json");
        // 获取输出流
        PrintWriter writer = response.getWriter();

        ObjectMapper mapper = new ObjectMapper();
        // 转为JSON字符串
        writer.write(mapper.writeValueAsString(result));
        // 刷新缓冲区并关闭流
        writer.flush();
        writer.close();
    }
    /**
     * 失败响参
     * @param response
     * @param result
     * @throws IOException
     */
    public static void fail(HttpServletResponse response, Response<?> result) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setStatus(HttpStatus.OK.value());
        response.setContentType("application/json");
        PrintWriter writer = response.getWriter();

        ObjectMapper mapper = new ObjectMapper();
        writer.write(mapper.writeValueAsString(result));
        writer.flush();
        writer.close();
    }

    /**
     * 失败响参
     * @param response
     * @param status 可指定响应码，如 401 等
     * @param result
     * @throws IOException
     */
    public static void fail(HttpServletResponse response, int status, Response<?> result) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setStatus(status);
        response.setContentType("application/json");
        PrintWriter writer = response.getWriter();

        ObjectMapper mapper = new ObjectMapper();
        writer.write(mapper.writeValueAsString(result));
        writer.flush();
        writer.close();
    }
}
